package com.loto.insurance.oem.web.utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import com.loto.insurance.oem.web.entity.WebserviceRequest;
import com.loto.insurance.oem.web.entity.WebserviceResponse;
import com.loto.utils.Http;
import com.loto.utils.XML;

public class Webservice {

	static Logger logger = LogManager.getLogger(Webservice.class);

	public WebserviceResponse Request(String func, Map<String, String> params) {
		WebserviceRequest request = new WebserviceRequest();
		request.setAcc("demo");
		request.setPin("demo11");
		request.setFunc(func);
		request.setParams(params);
		try {
			String xmlRequest = XML.toXML(request, WebserviceRequest.class);
			logger.error(xmlRequest);
			Map<String, String> paramMap = new HashMap<String, String>();
			paramMap.put("content", xmlRequest);
			String xmlResponse = Http.doPost(
					"http://localhost:8090/webservice/entry.service", paramMap);
			logger.error(xmlResponse);
			WebserviceResponse response = parseResponse(xmlResponse);

			logger.error(response.isOk());
			/*
			 * ArrayList<WebserviceRequest> o = result.getList(); for
			 * (WebserviceRequest map : o) { logger.error(map.getAcc());
			 * logger.error(map.get("acc")); logger.error(map.get("func")); }
			 */
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	
	private WebserviceResponse parseResponse(String xmlResponse) {
		WebserviceResponse response = new WebserviceResponse();
		ArrayList<Map<String, String>> listMap = new ArrayList<Map<String, String>>();
		try {
			Document doc = DocumentHelper.parseText(xmlResponse);
			Element rootElt = doc.getRootElement();
			response.setOk(rootElt.elementTextTrim("ok").equals("true") ? true
					: false);
			response.setMsg(rootElt.elementTextTrim("msg"));
			Iterator iter = rootElt.elementIterator("list");
			while (iter.hasNext()) {
				Map<String, String> map = new HashMap<String, String>();
				Element itemEle = (Element) iter.next();
				Iterator iters = itemEle.elementIterator();
				while (iters.hasNext()) {
					Element itemEles = (Element) iters.next();
					map.put(itemEles.getName(), itemEles.getTextTrim());
				}
				listMap.add(map);
			}
			response.setList(listMap);
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return response;
	}
}
